<template>
  <el-drawer
    v-model="drawerVisible"
    :destroy-on-close="true"
    size="700px"
    :title="`${drawerProps?.title}菜单`"
    @open="drawerOpen"
  >
    <el-form ref="editRef" :model="form" :rules="rules" label-width="100px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="上级部门">
            <el-tree-select
              v-model="form.parentId"
              :data="parentOptions"
              :props="{ value: 'deptId', label: 'deptName' }"
              value-key="deptId"
              placeholder="选择上级部门"
              clearable
              check-strictly
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="部门名称" prop="deptName">
            <el-input v-model="form.deptName" placeholder="请输入部门名称" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="显示排序" prop="orderNum">
            <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="负责人" prop="leader">
            <el-input v-model="form.leader" placeholder="请输入部门名称" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="form.phone" controls-position="right" type="tel" :min="0" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" controls-position="right" type="email" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="部门状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio label="0">启用</el-radio>
              <el-radio label="1">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false"> 取消 </el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit"> 确定 </el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="EditDrawer">
import { ref, reactive, toRefs, getCurrentInstance, ComponentInternalInstance } from "vue";
import SelectIcon from "@/components/SelectIcon/index.vue";
import { ElMessage, FormInstance } from "element-plus";
import { handleTree } from "@/utils";
import { SystemApi } from "@/api/modules";
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<IDept>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}
const parentOptions = ref<any[]>([]);
const drawerVisible = ref(false);
const showChooseIcon = ref(false);
const iconSelectRef = ref<any>(null);
const data = reactive<{
  form: any;
  queryParams: any;
  rules: any;
}>({
  form: {
    leader: "",
    orderNum: 1,
    phone: "",
    deptName: "",
    parentId: 0,
    status: "0",
    deptId: undefined,
    children: [],
    email: undefined,
  },
  queryParams: {
    deptName: undefined,
    visible: undefined,
  },
  rules: {
    deptName: [{ required: true, message: "名称不能为空", trigger: "blur" }],
    orderNum: [{ required: true, message: "菜单顺序不能为空", trigger: "blur" }],
  },
});
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {},
});
const { queryParams, form, rules } = toRefs(data);

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  if (Object.getOwnPropertyNames(params.row).length) {
    if (params.title == "编辑") {
      data.form = JSON.parse(JSON.stringify(params.row));
    }
    if (params.title == "新增") {
      (data.form = {
        leader: "",
        orderNum: 1,
        phone: "",
        deptName: "",
        parentId: 0,
        status: "0",
        deptId: undefined,
        children: [],
        email: undefined,
      }),
        (data.form.parentId = params.row.deptId);
    }
  }
  drawerVisible.value = true;
};
// drawer 打开时的事件
const drawerOpen = () => {
  getTreeSelect();
};
// 提交数据（新增/编辑）

const handleSubmit = () => {
  (proxy?.$refs["editRef"] as any).validate(async (valid: any) => {
    if (!valid) return;
    try {
      const payload = JSON.parse(JSON.stringify(data.form));
      if (!payload.parentId) {
        payload.parentId = 0;
      }
      if (payload.deptId) {
        await SystemApi.putDept(payload);
      } else {
        await SystemApi.addDept(payload);
      }
      ElMessage.success({ message: `${drawerProps.value.title}成功！` });
      drawerVisible.value = false;
      drawerProps.value.getTableList!();
    } catch (error) {
      console.log(error);
    }
  });

  // ruleFormRef.value!.validate(async valid => {
  //   if (!valid) return;
  //   try {
  //     await drawerProps.value.api!(drawerProps.value.row);
  //     ElMessage.success({ message: `${drawerProps.value.title}用户成功！` });
  //     drawerProps.value.getTableList!();
  //     drawerVisible.value = false;
  //   } catch (error) {
  //     console.log(error);
  //   }
  // });
};
const getTreeSelect = () => {
  parentOptions.value = [];
  SystemApi.getDeptList().then((res: any) => {
    let dept = handleTree(res.data, "deptId");

    const data = [
      {
        deptId: 0,
        deptName: "根类目",
        children: dept,
      },
    ];
    parentOptions.value = data;
  });
};

defineExpose({
  acceptParams,
});
</script>
